/** \file    pattern_match.cpp
  * \brief   Matching patterns in file names.
  * \date    2004
  * \author  Fedor Chelnokov
  * \version $Header: /home/cscom1r4/cvsroot/cs/mswin/src/pattern_match.cpp,v 1.1 2004/01/23 21:29:35 cscom1r4 Exp $
  */

#include <mswin/file_dir.h>

#ifdef NDEBUG
#define BOOST_REGEX_STATIC_LINK
#endif
#include "boost/regex.hpp"

namespace mswin {

bool pattern_match(const std::string & name, const std::string & pattern)
{
	std::string regex;
	regex.reserve(pattern.size() + 3); //for typical '*.*'
	bool quotation = false;
	for (int n = 0; n != pattern.size(); ++n) {
		char c = pattern[n];
		if (c == '"')
			quotation = !quotation;
		else if (!quotation && c == '?')
			regex.push_back('.');
		else if (!quotation && c == '*') {
			regex.push_back('.');
			regex.push_back('*');
		}
		else {
			switch (c) {
			case '.': case '|': case '*': case '?': case '+': case '(': case ')':
			case '{': case '}': case '[': case ']': case '^': case '$': case '\\':
				regex.push_back('\\');
			default:
				regex.push_back(c);
			}
		}
	}

	return regex_match(name, boost::regex(regex));
}

} //namespace mswin
